package zdh.avatar.softphone;

import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import net.sourceforge.peers.Config;
import net.sourceforge.peers.Logger;
import net.sourceforge.peers.gui.EventManager;
import net.sourceforge.peers.gui.Registration;
import net.sourceforge.peers.sip.RFC3261;
import net.sourceforge.peers.sip.core.useragent.UserAgent;
import net.sourceforge.peers.sip.syntaxencoding.SipURI;
import net.sourceforge.peers.sip.syntaxencoding.SipUriSyntaxException;
import net.sourceforge.peers.sip.transport.SipRequest;
import net.sourceforge.peers.sip.transport.SipResponse;

/**
 *
 * @author Gem Seeker
 */
public class Register extends javax.swing.JFrame {

    public final Softphone softphone;

    private String userpart;
    private String domain;
    private String password;
    private String outbound;
    private final UserAgent userAgent;
    private final EventManager eventManager;
    private final Registration registration;
    private final Logger logger;

    private boolean unregistering;

    public Register(Softphone softphone, Logger logger) {
        this.softphone = softphone;
        eventManager = softphone.eventManager;
        this.logger = logger;
        unregistering = false;
        userAgent = eventManager.userAgent;
        initComponents();
        registration = new Registration(lbl_reg, logger);
    }

    public void showWindow() {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                Config con = userAgent.getConfig();
                if (con != null) {
                    String acc = con.getUserPart() + "@" + con.getDomain();
                    tf_acc.setText(acc);
                    String pass = con.getPassword();
                    tf_pass.setText(pass);
                    String proxy = con.getOutboundProxy().toString();
                    tf_outbound.setText(proxy.substring("sip:".length()));
                }
                setLocationRelativeTo(null);
                setVisible(true);
            }
        });
    }

    // Registration
    private void applyNewConfig() {
        Config config = userAgent.getConfig();
        // 
        if (userpart != null) {
            config.setUserPart(userpart);
        }

        if (domain != null) {
            config.setDomain(domain);
        }

        if (password != null) {
            config.setPassword(password);
        }

        if (outbound != null) {
            SipURI sipURI;
            try {
                if ("".equals(outbound.trim())) {
                    config.setOutboundProxy(null);
                } else {
                    sipURI = new SipURI(outbound);
                    config.setOutboundProxy(sipURI);
                }
            } catch (SipUriSyntaxException e) {
                JOptionPane.showMessageDialog(this, e.getMessage());
                logger.error("sip uri syntax issue", e);
                return;
            }
        }
        config.save();
        unregistering = false;
        if (password != null) {
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    try {
                        userAgent.getUac().register();
                    } catch (SipUriSyntaxException e) {
                        JOptionPane.showMessageDialog(Register.this,
                                e.getMessage());
                        logger.error("sip uri syntax issue", e);
                    }
                }
            };
            Thread thread = new Thread(runnable);
            thread.start();
        }
    }

    public void registering(SipRequest sipRequest) {
        registration.registerSent();
    }

    public synchronized void registerSuccess(SipResponse sipResponse) {
        if (unregistering) {
            userAgent.close();
            applyNewConfig();
        } else {
            registration.registerSuccessful();
        }
    }

    public void registerFailed(SipResponse sipResponse) {
        if (unregistering) {
            userAgent.close();
            applyNewConfig();
        } else {
            registration.registerFailed();
        }
    }

    public void register() {
        Runnable runnable;
        if (userAgent.isRegistered()) {
            synchronized (this) {
                unregistering = true;
            }
            runnable = new Runnable() {
                @Override
                public void run() {
                    try {
                        userAgent.getUac().unregister();
                    } catch (SipUriSyntaxException e) {
                        logger.error("syntax error", e);
                    }
                }
            };
        } else {
            runnable = new Runnable() {
                @Override
                public void run() {
                    userAgent.close();
                    applyNewConfig();
                }
            };
        }
        SwingUtilities.invokeLater(runnable);
    }

    //<editor-fold defaultstate="collapsed" desc="Generated Codes">
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        tf_outbound = new javax.swing.JTextField();
        tf_acc = new javax.swing.JTextField();
        tf_pass = new javax.swing.JTextField();
        jSeparator1 = new javax.swing.JSeparator();
        btn_reg = new javax.swing.JButton();
        lbl_reg = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Register Account");
        setResizable(false);

        jLabel1.setText("SIP Account:");

        jLabel2.setText("Password:");

        jLabel3.setText("Outbound Proxy:");

        btn_reg.setText("Register");
        btn_reg.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_regActionPerformed(evt);
            }
        });

        lbl_reg.setText("Registration");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tf_outbound))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(33, 33, 33)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tf_pass, javax.swing.GroupLayout.DEFAULT_SIZE, 220, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(21, 21, 21)
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tf_acc, javax.swing.GroupLayout.DEFAULT_SIZE, 220, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(lbl_reg, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGap(18, 18, 18)
                        .addComponent(btn_reg)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(tf_acc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(tf_pass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tf_outbound, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btn_reg)
                    .addComponent(lbl_reg))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btn_regActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_regActionPerformed
        String acc = tf_acc.getText();
        userpart = acc.substring(0, acc.indexOf("@"));
        domain = acc.substring(acc.indexOf("@") + 1);
        password = tf_pass.getText();
        outbound = "sip:" + tf_outbound.getText();
        register();
    }//GEN-LAST:event_btn_regActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btn_reg;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JLabel lbl_reg;
    private javax.swing.JTextField tf_acc;
    private javax.swing.JTextField tf_outbound;
    private javax.swing.JTextField tf_pass;
    // End of variables declaration//GEN-END:variables
    //</editor-fold>
}
